package com.yuntsg.subject_database.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Code {
    private String code = "";
    //验证码长度
    private int codeLength;

    //md5加密
    public static String digestData(String dataStr) {
        if (dataStr != null) {
            MessageDigest md = null;
            try {
                md = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            md.update(dataStr.getBytes());
            return getHexString(md.digest());
        } else {
            return null;
        }
    }

    private static String getHexString(byte[] b) {
        if (b != null) {
            char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < b.length; i++) {
                result.append(digits[(b[i] >> 4) & 0x0F]);
                result.append(digits[b[i] & 0x0F]);
            }
            return result.toString();
        } else {
            return "";
        }
    }

    public String createCode(int codeLength) {
        for (int i = 0; i < codeLength; i++) {
            code += String.valueOf((int) (Math.random() * 9)).toString();
        }


        return code;
    }

}
